package com.wz.project.bas.product.controller;

import com.wz.common.exception.BusinessException;
import com.wz.common.utils.StringUtils;
import com.wz.common.utils.poi.ExcelUtil;
import com.wz.framework.web.controller.BaseController;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.framework.web.page.TableDataInfo;
import com.wz.project.bas.product.domain.Product;
import com.wz.project.bas.product.service.IProductService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 基础物品 信息操作处理
 * 
 * @author sys
 * @date 2021-10-28
 */
@Controller
@RequestMapping("/bas/product")
public class ProductController extends BaseController
{

	private final static Map<Integer, Product> products = new LinkedHashMap<Integer, Product>();
    private String prefix = "bas/product";
	
	@Autowired
	private IProductService productService;

	
	@RequiresPermissions("bas:product:view")
	@GetMapping()
	public String product()
	{
	    return prefix + "/product";
	}

	@RequiresPermissions("system:basProduct:view")
	@GetMapping("/selectProduct")
	public String selectProductId()
	{
		return  "/stock/stock/selectProduct";
	}
	/**
	 * 查询基础物品列表
	 */
//	@RequiresPermissions("module:product:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Product product)
	{
		startPage();
        List<Product> list = productService.selectProductList(product);
		return getDataTable(list);
	}



	
	/**
	 * 新增保存基础物品
	 */
	@RequiresPermissions("module:product:add")
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Product product)
	{
		String s = String.valueOf(System.currentTimeMillis());
		String substring = s.substring(s.length() - 6);
//        int pejId = Integer.parseInt(substring);
		product.setProductGuid(substring);
		return toAjax(productService.insertProduct(product));
	}

	/**
	 * 修改基础物品
	 */
	@GetMapping("/edit/{productGuid}")
	public String edit(@PathVariable("productGuid") String productGuid, ModelMap mmap)
	{
		Product product = productService.selectProductById(productGuid);
		mmap.put("product", product);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存基础物品
	 */
	@RequiresPermissions("module:product:edit")
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Product product)
	{		
		return toAjax(productService.updateProduct(product));
	}
	
	/**
	 * 删除基础物品
	 */
	@RequiresPermissions("module:product:remove")
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		return toAjax(productService.deleteProductByIds(ids));
	}


	/**
	 * 下载模板
	 */
	@GetMapping("/importTemplate")
	@ResponseBody
	public AjaxResult importTemplate()
	{
		ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
		return util.importTemplateExcel("物料信息");
	}

	/**
	 * 导入数据
	 */
	@PostMapping("/importData")
	@ResponseBody
	public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
	{
		ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
		List<Product> productList = util.importExcel(file.getInputStream());

		String message = importUser(productList, updateSupport); 
		return AjaxResult.success(message);
	}

	/**
	 * 导入用户数据
	 *
	 * @param productList 用户数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @return 结果
	 */
	public String importUser(List<Product> productList, Boolean isUpdateSupport)
	{
		if (StringUtils.isNull(productList) || productList.size() == 0)
		{
			throw new BusinessException("导入数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for (Product product : productList)
		{
			try
			{
				// 验证是否存在这个用户
				boolean userFlag = false;
				for (Map.Entry<Integer, Product> entry : products.entrySet())
				{
					if (entry.getValue().getProductId().equals(product.getProductId()))
					{
						userFlag = true;
						break;
					}
				}
				if (!userFlag)
				{
					String productGuid = UUID.randomUUID().toString();
					product.setProductGuid(productGuid);
					product.setProductHeight(new BigDecimal(1));
					product.setProductWidth(new BigDecimal(1));
					product.setProductLength(new BigDecimal(1));
					productService.insertProduct(product);
     				products.put(Integer.valueOf(product.getProductId()), product);
					successNum++;
					successMsg.append("<br/>" + successNum + "、物料 " + product.getProductName() + " 导入成功");
				}
				else if (isUpdateSupport)
				{
					products.put(Integer.valueOf(product.getProductId()), product);
					successNum++;
					successMsg.append("<br/>" + successNum + "、物料 " + product.getProductName() + " 更新成功");
				}
				else
				{
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、物料 " + product.getProductName() + " 已存在");
				}
			}
			catch (Exception e)
			{
				failureNum++;
				String msg = "<br/>" + failureNum + "、物料 " + product.getProductName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
			}
		}
		if (failureNum > 0)
		{
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new BusinessException(failureMsg.toString());
		}
		else
		{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
}
